import {Component} from "react";

export default class TestState extends Component{
    constructor(props){
        super(props);
        this.state = {
            name: "katy",
            age: 30
        }
        this.changeUser = this.changeUser.bind(this);
        console.log("state constructor");
    }

    shouldComponentUpdate(){
        console.log("shouldComponentUpdate");
        return true;
    }

    componentWillUpdate(){
        console.log("componentWillUpdate");
    }

    componentDidUpdate(){
        console.log("componentDidUpdate");
    }

    changeUser(e){
        var name = this.state.name=="katy"?"win7":"katy";
        var age = this.state.age+1;
        this.setState({
            name,
            age
        });
        //setState 传递函数应该是针对同时更改两个属性 a、b 的值，属性b 的值依赖于属性a 更改后的值(我觉得传递函数也没有解决问题啊)
        this.setState((prevState, prevProps)=>{
            console.log(prevState);
            return {
                name: prevState.name=="katy"?"win7":"katy",
                age: prevState.age + 1
            }
        },()=>{
            console.log("-----in-----");
            console.log("name:");
            console.log(document.getElementById("name").innerHTML);
            console.log("age:");
            console.log(document.getElementById("age").innerHTML);
        });
        console.log("-----out-----");
        console.log("name:");
        console.log(document.getElementById("name").innerHTML);
        console.log("age:");
        console.log(document.getElementById("age").innerHTML);
    }
    hello(){}

    render(){
        console.log("render");
        return (
            <div>
                <div id="name" ref={ref=>this.name=ref}>{this.state.name}</div>
                <div id="age" ref="age">{this.state.age}</div>
                <div>
                    <button onClick={function(){
                        console.log("this:");
                        console.log(this);
                    }}>test this</button>
                    <button onClick={this.changeUser}>change user</button>
                </div>
            </div>
        )
    }
}